package org.teremail.message.builder;

import org.teremail.message.Content;
import org.teremail.message.ContentHeaders;
import org.teremail.message.Entity;
import org.teremail.message.MessageHeaders;
import org.teremail.message.SimpleMessage;

public class SimpleMessageBuilder implements ContentEntityBuilder, MessageBuilder {

    private Content content;
    private ContentHeaders contentHeader;
    private final MessageHeadersBuilder headersBuilder;
    private String id = Entity.UNSAVED_ID;
    private SimpleMessage original;
    private boolean hasChanged = true;
    
    public SimpleMessageBuilder(ContentHeaders contentHeader, 
            MessageHeadersBuilder headersBuilder, Content content) {
        this.contentHeader = contentHeader;
        this.headersBuilder = headersBuilder;
        this.content = content;
    }
    
    public SimpleMessageBuilder(SimpleMessage simpleMessage) {
        this(simpleMessage.getContentHeader(), 
                new MessageHeadersBuilder(simpleMessage.getHeader()), 
                simpleMessage.getContent());
        this.original = simpleMessage;
        hasChanged = false;
    }

    public SimpleMessageBuilder() {
        this(null, new MessageHeadersBuilder(), null);
    }

    public SimpleMessageBuilder setContent(Content content) {
        hasChanged = true;
        this.content = content;
        return this;
    }

    public SimpleMessageBuilder setId(String id) {
        hasChanged = true;
        this.id = id;
        return this;
    }
    
    public String getId() {
        return id;
    }

    public MessageHeadersBuilder getHeaderBuilder() {
        return headersBuilder;
    }
    
    public boolean hasChanged() {
        return hasChanged || original == null || headersBuilder.hasChanged();
    }
    
    public SimpleMessage build() {
        if (hasChanged()) {
            MessageHeaders header = headersBuilder.build();
            SimpleMessage message = new SimpleMessage(id, contentHeader, header, content);
            return message;
        } else {
            return original;
        }
    }

    public void setHeaders(String messageHeaders) {
        headersBuilder.load(messageHeaders);
    }

    public boolean isMultipart() {
        return false;
    }

}
